package com.maxvision.mybatis.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类说明
 *
 * @author HuangRongFu
 * @date 2022/11/23
 */

@Component
@Aspect
@Order(1)
@Log4j2
public class LogAspect {
    
    @Pointcut("execution(* com.maxvision.mybatis.controller..*.*(..))")
    public void LogAspect(){}
    
    @Before(value = "LogAspect()")
    public void before(JoinPoint joinPoint){

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        
        log.info("请求日志打印");
        log.info("请求地址:{}", request.getRequestURI());
        log.info("请求方法:{}",joinPoint.getSignature());
        log.info("请求方式:{}", request.getMethod());
        log.info("请求参数:{}",  JSONObject.toJSONString(JSONObject.toJSONString(filterArgs(joinPoint.getArgs()))));
        log.info("请求参数:{}",  joinPoint.getArgs());
    }

    private List<Object> filterArgs(Object[] objects) {
        return Arrays.stream(objects).filter(obj -> !(obj instanceof MultipartFile[])
                && !(obj instanceof MultipartFile)
                && !(obj instanceof HttpServletResponse)
                && !(obj instanceof HttpServletRequest)).collect(Collectors.toList());
    }
    
}
